package com.programmercarl.string;

/**
 * https://leetcode.cn/problems/reverse-string-ii/description/
 *
 * @author yulongtian
 * @create 2024-12-15 11:09
 */
public class Test02 {
    public static void main(String[] args) {
        Test02 test02 = new Test02();
        System.out.println(test02.reverseStr("abcd", 2));
    }

    public String reverseStr(String s, int k) {
        char[] chs = s.toCharArray();
        int i = 0;
        while (true) {
            if (i + 2 * k <= chs.length) {
                mySwap(chs, i, i + k - 1);
                i += 2 * k;
                continue;
            }
            if (i + k <= chs.length && i + 2 * k > chs.length) {
                mySwap(chs, i, i + k - 1);
                break;
            }
            if (i + k > chs.length) {
                mySwap(chs, i, chs.length - 1);
                break;
            }
        }

        return new String(chs);
    }

    public void mySwap(char[] chs, int i, int j) {
        while (i < j) {
            char temp = chs[i];
            chs[i] = chs[j];
            chs[j] = temp;
            i++;
            j--;
        }
    }
}
